package com.code.cheney.shiro.service.impl;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.filter.AutoLoad;
import com.code.cheney.shiro.dao.UserDao;
import com.code.cheney.shiro.entity.User;
import com.code.cheney.shiro.service.UserService;

/**
 * 
 * Project: shiro Class: UserServiceImpl Description:
 * 
 * @author: Cheney
 * @Date 2016年6月30日 下午9:17:08
 * @version 1.0
 * 
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private PasswordHelper passwordHelper;

	/**
	 * 创建用户
	 * 
	 * @param user
	 */
	public User createUser(User user) {
		// 加密密码
		passwordHelper.encryptPassword(user);
		Long id = userDao.createUser(user);
		user.setId(id);
		return user;
	}

	/**
	 * 修改密码
	 * 
	 * @param userId
	 * @param newPassword
	 */
	public void changePassword(Long userId, String newPassword) {
		User user = userDao.findOne(userId);
		user.setPassword(newPassword);
		passwordHelper.encryptPassword(user);
		userDao.updateUser(user);
	}

	/**
	 * 添加用户-角色关系
	 * 
	 * @param userId
	 * @param roleIds
	 */
	public void correlationRoles(Long userId, Long... roleIds) {
		if (roleIds == null || roleIds.length == 0) {
			return;
		}
		for (Long roleId : roleIds) {
			if (!exists(userId, roleId)) {
				userDao.correlationRoles(userId, roleId);
			}
		}
	}

	/**
	 * 移除用户-角色关系
	 * 
	 * @param userId
	 * @param roleIds
	 */
	public void uncorrelationRoles(Long userId, Long... roleIds) {
		if (roleIds == null || roleIds.length == 0) {
			return;
		}
		for (Long roleId : roleIds) {
			if (exists(userId, roleId)) {
				userDao.uncorrelationRoles(userId, roleId);
			}
		}
	}

	/**
	 * 根据用户名查找用户
	 * 
	 * @param username
	 * @return
	 */
	public User findByUsername(String username) {
		return userDao.findByUsername(username);
	}

	/**
	 * 根据用户名查找其角色
	 * 
	 * @param username
	 * @return
	 */
	public Set<String> findRoles(String username) {
		return userDao.findRoles(username);
	}

	/**
	 * 根据用户名查找其权限
	 * 
	 * @param username
	 * @return
	 */
	public Set<String> findPermissions(String username) {
		return userDao.findPermissions(username);
	}

	private boolean exists(Long userId, Long roleId) {
		return userDao.exists(userId, roleId);
	}

	public void delete() {
		userDao.delete1();
		userDao.delete2();
		userDao.delete3();
		userDao.delete4();
		userDao.delete5();
	}
}
